package server;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import server.clients.Client;
import server.clients.ClientList;

public class httpRequestHandler implements Runnable {
	final static String CRLF = "\r\n";
	Socket socket;
	InputStream input;
	OutputStream output;
	BufferedReader br;

	public httpRequestHandler(Socket socket) throws Exception {
		this.socket = socket;
		this.input = socket.getInputStream();
		this.output = socket.getOutputStream();
		this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	}

	public void run() {
		try {
			processRequest();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void processRequest() throws Exception {
		int i=0;
		while (true) {
			String headerLine = br.readLine();
//			System.out.println(headerLine);
			if (headerLine.equals(CRLF) || headerLine.equals(""))
				break;
			StringTokenizer s = new StringTokenizer(headerLine);
			String temp = s.nextToken();
			String header = "HTTP/1.0 200 OK\r\nServer: Masspäringud\r\nContent-type: text/html\r\n\r\n";
			if (temp.equals("GET")) {
				String fileName = s.nextToken(), commandStr = "", content="";
				if(fileName.indexOf("?")>-1){
					commandStr = fileName.substring(1,fileName.indexOf("?"));
					System.out.println(socket.getInetAddress().getHostAddress() + " " + commandStr);
					if(commandStr.equals("URL")){
						String url = fileName.substring(fileName.indexOf("url=")+4);
						System.out.println(url);
						List<String> res = Command.openUrl(url);
						for (String string : res){
							content += string;
						}
					}
					else if(commandStr.equals("SENDTASK")){
						String url = fileName.substring(fileName.indexOf("urls=")+5);
						System.out.println(url);
						String[] urls = url.split("\\)\\(");
						urls[0] = urls[0].substring(2);
						urls[urls.length-1] = urls[urls.length-1].substring(0, urls[urls.length-1].length()-2); 
						int loend=0;
						String cmd="";
						List<String> tasks = new ArrayList<String>();
						for (String string : urls) {
							if(loend==0)
								cmd = "[(";
							cmd += string;
							loend++;
							if(loend <10)
								cmd +=")(";
							if(loend==10){
								tasks.add(cmd);
//								Command.openUrl("http://localhost:5500/SENDURLS?urls=" + cmd+")]");
								loend=0;
							}
						}
						if(loend != 10)
							tasks.add(cmd);
						
					}
					else if(commandStr.equals("SENDURLS")){
						System.out.println(i++);
						String url = fileName.substring(fileName.indexOf("urls=")+5);
						System.out.println(url);
						String[] urls = url.split("\\)\\(");
						urls[0] = urls[0].substring(2);
						urls[urls.length-1] = urls[urls.length-1].substring(0, urls[urls.length-1].length()-2); 
						for (String string : urls) {
							System.out.println(string);
						}
					}
					else if(commandStr.equals("ADDME")){
						String address = fileName.substring(fileName.indexOf("adr=")+4);
						String ip = socket.getInetAddress().getHostAddress();
						String port = address.substring(address.indexOf(':')+1);
//						System.out.println(address);
//						System.out.println(ip);
//						System.out.println(port);
						String result="";
						List<Client> clientList = HttpServer.getClientList().addClient(ip, Integer.parseInt(port));
						for (Client client : clientList) {
							String clientStr = client.getIp() + ":" + client.getPort();
							if (!clientStr.equals(ip + ":" + port)){
								if(!ip.equals("127.0.0.1") && client.getIp().equals("127.0.0.1"))
									result += socket.getLocalAddress().getHostAddress() + ":" + client.getPort() +";";
								else
									result += clientStr+";";
								Command.openUrl("http://" + clientStr + "/ADDCLIENT?adr=" + ip + ":" + port);
								System.out.println(clientStr + "/ADDCLIENT?adr=" + ip + ":" + port);
							}
						}
						result += socket.getLocalAddress().getHostAddress() + ":" + HttpServer.getPort() + ";";
						if(!result.equals(""))
						{
							System.out.println(ip + ":" + port+"/ADDCLIENTS?adr=" +result.substring(0, result.length()-1));
							Command.openUrl("http://" + ip + ":" + port+"/ADDCLIENTS?adr=" +result.substring(0, result.length()-1));
						}
						
					}
					else if(commandStr.equals("ADDCLIENT")){
						String address = fileName.substring(fileName.indexOf("adr=")+4);
						String ip = address.substring(0, address.indexOf(':'));
						String port = address.substring(address.indexOf(':')+1);
						System.out.println(address);
//						System.out.println(ip);
//						System.out.println(port);
						HttpServer.getClientList().addClient(ip, Integer.parseInt(port));
					}
					else if(commandStr.equals("ADDCLIENTS")){
						String address = fileName.substring(fileName.indexOf("adr=")+4);
						String[] addresses = address.split(";");
						for (String adr : addresses) {
							String ip = adr.substring(0, adr.indexOf(':'));
							String port = adr.substring(adr.indexOf(':')+1);
							System.out.println(adr);
//							System.out.println(ip);
//							System.out.println(port);
							HttpServer.getClientList().addClient(ip, Integer.parseInt(port));							
						}				
					}
					else if(commandStr.equals("PING")){
						content = "PONG";
					}
					
				}
				output.write(header.getBytes());
				output.write(content.getBytes());
			}
		}
		output.close();
		br.close();
		socket.close();
	}
}